const Keyword = require('../models/Keyword');
const Site = require('../models/Site');
const ErrorResponse = require('../utils/errorResponse');

// @desc    添加关键词
// @route   POST /api/keywords
// @access  Private
const addKeyword = async (req, res) => {
  try {
    const { keyword, siteId } = req.body;
    const userId = req.user.id;

    // 检查网站是否存在
    const site = await Site.findById(siteId);
    if (!site) {
      return res.status(404).json({ 
        status: 'error', 
        message: '网站不存在' 
      });
    }

    // 确保用户拥有该网站
    if (site.user.toString() !== userId) {
      return res.status(401).json({ 
        status: 'error', 
        message: '未授权为此网站添加关键词' 
      });
    }

    // 创建关键词记录
    const newKeyword = await Keyword.create({
      user: userId,
      site: siteId,
      keyword
    });

    res.status(201).json({
      status: 'success',
      data: newKeyword
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// @desc    获取用户所有关键词
// @route   GET /api/keywords
// @access  Private
const getKeywords = async (req, res) => {
  try {
    const keywords = await Keyword.find({ user: req.user.id })
      .populate('site', 'name url');
    
    res.status(200).json({
      status: 'success',
      data: keywords
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// @desc    获取关键词统计数据
// @route   GET /api/keywords/:id/stats
// @access  Private
const getKeywordStats = async (req, res) => {
  try {
    const { id } = req.params;

    const keyword = await Keyword.findById(id);
    if (!keyword) {
      return res.status(404).json({ 
        status: 'error', 
        message: '关键词不存在' 
      });
    }

    // 确保用户拥有该关键词
    if (keyword.user.toString() !== req.user.id) {
      return res.status(401).json({ 
        status: 'error', 
        message: '未授权访问此关键词' 
      });
    }

    res.status(200).json({
      status: 'success',
      data: keyword.stats
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// @desc    分析关键词
// @route   POST /api/keywords/analyze
// @access  Private
const analyzeKeyword = async (req, res) => {
  try {
    const { keyword, siteId } = req.body;
    const userId = req.user.id;

    // 检查网站是否存在
    const site = await Site.findById(siteId);
    if (!site) {
      return res.status(404).json({ 
        status: 'error', 
        message: '网站不存在' 
      });
    }

    // 确保用户拥有该网站
    if (site.user.toString() !== userId) {
      return res.status(401).json({ 
        status: 'error', 
        message: '未授权为此网站分析关键词' 
      });
    }

    // 模拟关键词分析结果
    const analysisResult = {
      keyword,
      searchVolume: Math.floor(Math.random() * 10000),
      difficulty: Math.floor(Math.random() * 100),
      cpc: (Math.random() * 10).toFixed(2),
      serpFeatures: {
        hasAds: Math.random() > 0.5,
        hasVideo: Math.random() > 0.3,
        hasFeaturedSnippet: Math.random() > 0.2
      },
      relatedKeywords: generateRelatedKeywords(keyword),
      timestamp: new Date()
    };

    res.status(200).json({
      status: 'success',
      data: analysisResult
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// @desc    追踪关键词排名
// @route   POST /api/keywords/track-ranking
// @access  Private
const trackKeywordRanking = async (req, res) => {
  try {
    const { keywordId } = req.body;
    const userId = req.user.id;

    // 查找关键词
    const keyword = await Keyword.findById(keywordId).populate('site', 'url');
    if (!keyword) {
      return res.status(404).json({ 
        status: 'error', 
        message: '关键词不存在' 
      });
    }

    // 确保用户拥有该关键词
    if (keyword.user.toString() !== userId) {
      return res.status(401).json({ 
        status: 'error', 
        message: '未授权追踪此关键词' 
      });
    }

    // 模拟关键词排名追踪结果
    const currentRank = Math.floor(Math.random() * 100);
    const bestRank = keyword.stats.bestRank 
      ? Math.min(keyword.stats.bestRank, currentRank)
      : currentRank;

    // 更新关键词统计数据
    keyword.stats.currentRank = currentRank;
    keyword.stats.bestRank = bestRank;
    keyword.trackingHistory.push({
      rank: currentRank,
      change: keyword.stats.currentRank 
        ? keyword.stats.currentRank - currentRank 
        : 0
    });
    await keyword.save();

    const trackingResult = {
      keyword: keyword.keyword,
      siteUrl: keyword.site.url,
      currentRank,
      bestRank,
      rankingHistory: keyword.trackingHistory,
      competitors: generateCompetitorAnalysis(keyword.keyword),
      timestamp: new Date()
    };

    res.status(200).json({
      status: 'success',
      data: trackingResult
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message 
    });
  }
};

// 生成相关关键词的辅助函数
const generateRelatedKeywords = (seedKeyword) => {
  const prefixes = ['best', 'how to', 'where to', 'why', 'what is'];
  const suffixes = ['2023', 'near me', 'guide', 'tips', 'reviews'];
  
  const related = [];
  
  // 添加前缀变体
  prefixes.forEach(prefix => {
    related.push(`${prefix} ${seedKeyword}`);
  });
  
  // 添加后缀变体
  suffixes.forEach(suffix => {
    related.push(`${seedKeyword} ${suffix}`);
  });
  
  // 添加LSI关键词
  related.push(...getLSIKeywords(seedKeyword));
  
  return related.slice(0, 10); // 返回前10个相关关键词
};

// 获取LSI关键词的辅助函数
const getLSIKeywords = (keyword) => {
  // 这是一个简化的示例，实际应用中应该使用更复杂的算法或API
  const lsiMap = {
    'seo': ['search engine optimization', 'google ranking', 'website traffic', 'backlinks', 'on-page seo'],
    'marketing': ['digital marketing', 'social media', 'branding', 'advertising', 'content strategy'],
    'web design': ['ux design', 'responsive design', 'user interface', 'website development', 'html css']
  };
  
  return lsiMap[keyword.toLowerCase()] || [];
};

// 生成排名历史的辅助函数
const generateRankingHistory = () => {
  const history = [];
  const days = 30;
  
  for (let i = 0; i < days; i++) {
    history.push({
      date: new Date(Date.now() - (days - i) * 24 * 60 * 60 * 1000),
      rank: Math.floor(Math.random() * 100),
      change: i > 0 ? history[i-1].rank - Math.floor(Math.random() * 10) + 5 : 0
    });
  }
  
  return history;
};

// 生成竞争对手分析的辅助函数
const generateCompetitorAnalysis = (keyword) => {
  const competitors = [];
  const competitorCount = Math.floor(Math.random() * 5) + 3; // 3-7个竞争对手
  
  for (let i = 0; i < competitorCount; i++) {
    competitors.push({
      domain: `competitor${i+1}.com`,
      rank: Math.floor(Math.random() * 10) + 1,
      backlinks: Math.floor(Math.random() * 1000),
      domainAuthority: Math.floor(Math.random() * 100),
      pageSpeed: Math.floor(Math.random() * 100),
      contentLength: Math.floor(Math.random() * 2000) + 500
    });
  }
  
  return competitors;
};

module.exports = {
  addKeyword,
  getKeywords,
  getKeywordStats,
  analyzeKeyword,
  trackKeywordRanking
};